package cc.sunwl.security.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

	@GetMapping(value = { "/" })
	public String index() {
		return "index";
	}

	@GetMapping("/home")
	@ResponseBody
	public List<String> home() {
		List<String> hostnames = new LinkedList<String>();
		String hostname = "";
		try {
			hostname = (InetAddress.getLocalHost()).getHostName();
		} catch (UnknownHostException uhe) {
			String host = uhe.getMessage(); // host = "hostname: hostname"
			if (host != null) {
				int colon = host.indexOf(':');
				if (colon > 0) {
					hostname = host.substring(0, colon);
				}
			}
		}
		hostnames.add("ForLiunx:" + hostname);
		String getenv = System.getenv("COMPUTERNAME");
		hostnames.add("ForWindows:" + getenv);
		return hostnames;
	}

	@PreAuthorize("hasAnyRole('ADMIN', 'USER')")
	@GetMapping("/hello")
	public String hello() {
		return "hello";
	}

	@PreAuthorize("hasAnyRole('ADMIN')")
	@GetMapping("/manager")
	public String manager() {
		return "manager";
	}
}
